package com.all.diy.utils
import android.content.Context
import android.os.Build
import android.os.Environment
import android.util.Log
import java.io.File
import java.io.IOException

object StorageUtils {
    private const val TAG = "StorageUtils"
    /**
     * 获取安全的外部存储目录
     * @param context 上下文
     * @param type 存储类型（如 Environment.DIRECTORY_DOCUMENTS）
     * @return 有效的File对象或null
     */
    @JvmStatic
    fun getSafeExternalFilesDir(context: Context, type: String? = null): File? {
        val externalDir = context.getExternalFilesDir(type)
        return if (externalDir != null && externalDir.exists()) {
            externalDir
        } else {
            //尝试创建目录
            val createdDir = File(context.getExternalFilesDir(null), type ?: "").apply {
                if (!exists()) mkdirParents()
            }
            if (createdDir.isDirectory) createdDir else null
        }
    }

    /**
     * 安全写入数据到外部存储
     * @param context 上下文
     * @param fileName 文件名
     * @param data 要写入的数据
     * @param type 存储类型
     * @throws IOException 当存储空间不足或写入失败时抛出
     */
    @JvmStatic
    @Throws(IOException::class)
    fun writeDataSafely(
        context: Context,
        fileName: String,
        data: String,
        type: String? = null
    ) {
        val targetDir = getSafeExternalFilesDir(context, type) ?: throw IOException("Invalid storage directory")
        val targetFile = File(targetDir, fileName)
        //检查存储状态和可用空间
        validateStorageAvailability(targetDir)
        checkAvailableSpace(targetDir, data.toByteArray().size.toLong())
        //使用use函数自动关闭流
        try {
            targetFile.outputStream().use { output ->
                output.bufferedWriter().use { writer ->
                    writer.write(data)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Write failed: ${e.message}")
            throw IOException("File write error", e)
        }
    }

    /**
     * 验证存储可用性
     */
    private fun validateStorageAvailability(dir: File) {
        val state = Environment.getExternalStorageState(dir)
        if (state != Environment.MEDIA_MOUNTED &&
            state != Environment.MEDIA_MOUNTED_READ_ONLY) {
            throw IOException("Storage not available. State: $state")
        }
    }

    /**
     * 检查可用空间
     * @param requiredBytes 所需字节数
     */
    private fun checkAvailableSpace(dir: File, requiredBytes: Long) {
        val freeSpace = dir.freeSpace
        if (freeSpace < requiredBytes * 2) { // 预留2倍空间
            throw IOException("Insufficient storage space. Required: $requiredBytes, Available: $freeSpace")
        }
    }

    /**
     * 递归创建目录（包括父目录）
     */
    fun File.mkdirParents(): Boolean {
        return if (!exists()) {
            parentFile?.mkdirParents() ?: false
            mkdirs()
        } else {
            true
        }
    }

    /**
     * 清理旧文件
     * @param daysThreshold 清理阈值（天）
     */
    @JvmStatic
    fun cleanOldFiles(context: Context, daysThreshold: Int) {
        try {
            val cacheDir = context.getExternalFilesDir(null) ?: return
            //Log.i("photoFile",cacheDir.path);
            cacheDir.listFiles()?.forEach { file ->
                //Log.i("photoFile",file.path+"&ile.lastModified()="+file.lastModified());
                if (file.isFile &&
                    System.currentTimeMillis() - file.lastModified() >
                    daysThreshold * 24L * 60 * 60 * 1000
                ) {
                    file.delete()
                    Log.d(TAG, "Deleted old file: ${file.name}")
                }
            }
        }catch (e: Exception){

        }
    }

    /**
     * 获取应用私有外部存储根目录
     */
    @JvmStatic
    fun getAppExternalRootDir(context: Context): File? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 使用应用私有目录
            context.getExternalFilesDir(null)
        } else {
            // 旧版本需要外部存储根目录
            Environment.getExternalStorageDirectory()?.apply {
                if (!exists()) mkdirParents()
            }
        }
    }
}